package com.atguigu.serviceedu.service.impl;

import com.atguigu.serviceedu.client.VodClient;
import com.atguigu.serviceedu.entity.*;
import com.atguigu.serviceedu.entity.coursevo.CourseInfoVo;
import com.atguigu.serviceedu.entity.coursevo.CoursePublish;
import com.atguigu.commonutils.exception.GuliException;
import com.atguigu.serviceedu.entity.coursevo.CourseQueryVo;
import com.atguigu.serviceedu.entity.coursevo.CourseWebVo;
import com.atguigu.serviceedu.mapper.EduCourseMapper;
import com.atguigu.serviceedu.service.EduChapterService;
import com.atguigu.serviceedu.service.EduCourseDescriptionService;
import com.atguigu.serviceedu.service.EduCourseService;
import com.atguigu.serviceedu.service.EduVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author xuan
 * @since 2020-04-14
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    EduCourseDescriptionService descriptionService;
    @Autowired
    EduVideoService videoService;
    @Autowired
    EduChapterService chapterService;
    @Autowired
    VodClient vodClient;

    @Override
    public String editCourse(CourseInfoVo courseInfo) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfo,eduCourse);
        EduCourseDescription courseDescription = new EduCourseDescription();
        BeanUtils.copyProperties(courseInfo,courseDescription);
        int result = 0;
        if(StringUtils.isEmpty(courseInfo.getId())){
            result = baseMapper.insert(eduCourse);
            if(result != 1){
                throw new GuliException(2001,"添加课程失败");
            }
            String courseId = eduCourse.getId();
            courseDescription.setId(courseId);
            descriptionService.save(courseDescription);
        }else{
            result = baseMapper.updateById(eduCourse);
            if(result != 1){
                throw new GuliException(2001,"更新课程失败");
            }
            descriptionService.updateById(courseDescription);
        }

        return eduCourse.getId();
    }

    @Override
    public CourseInfoVo getCourseInfoVo(String courseId) {
        EduCourse eduCourse = baseMapper.selectById(courseId);
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        if(eduCourse != null){
            BeanUtils.copyProperties(eduCourse,courseInfoVo);
        }
        EduCourseDescription description = descriptionService.getById(courseId);
        if(description != null){
            BeanUtils.copyProperties(description,courseInfoVo);
        }
        return courseInfoVo;
    }

    @Override
    public CoursePublish getCoursePublishById(String courseId) {
        return baseMapper.getCoursePublishById(courseId);
    }

    @Override
    public boolean deleteCourse(String courseId) {
        //视频
        QueryWrapper<EduVideo> videoWrapper = new QueryWrapper<>();
        videoWrapper.eq("course_id",courseId);
        List<EduVideo> videoList = videoService.list(videoWrapper);
        List<String> sourceIdList = new ArrayList<>();
        for (EduVideo video : videoList) {
            sourceIdList.add(video.getVideoSourceId());
        }
        vodClient.deleteVideoFile(sourceIdList);
        videoService.remove(videoWrapper);
        //课程详情
        descriptionService.removeById(courseId);
        //章节
        QueryWrapper<EduChapter> chapterWrapper = new QueryWrapper<>();
        chapterWrapper.eq("course_id",courseId);
        chapterService.remove(chapterWrapper);
        //课程
        int result = baseMapper.deleteById(courseId);
        return  result > 0;
    }

    @Override
    public boolean publish(String courseId) {
        EduCourse course = baseMapper.selectById(courseId);
        course.setStatus("Normal");
        int result = baseMapper.updateById(course);
        return result > 0;
    }

    @Cacheable(value = "hotCourses", key = "'selectIndexList'")
    @Override
    public List<EduCourse> getHotCourses() {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("buy_count").last("limit 4");
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<EduCourse> selectByTeacherId(String teacherId) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<EduCourse>();

        queryWrapper.eq("teacher_id", teacherId);
        //按照最后更新时间倒序排列
        queryWrapper.orderByDesc("gmt_modified");

        List<EduCourse> courses = baseMapper.selectList(queryWrapper);
        return courses;
    }

    @Override
    public Map<String, Object> pageListWeb(Page<EduCourse> pageParam, CourseQueryVo courseQuery) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseQuery.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", courseQuery.getSubjectParentId());
        }

        if (!StringUtils.isEmpty(courseQuery.getSubjectId())) {
            queryWrapper.eq("subject_id", courseQuery.getSubjectId());
        }

        if (!StringUtils.isEmpty(courseQuery.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(courseQuery.getGmtCreateSort())) {
            queryWrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseQuery.getPriceSort())) {
            queryWrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageParam, queryWrapper);

        List<EduCourse> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    @Override
    public CourseWebVo selectInfoWebById(String id) {
        this.updatePageViewCount(id);
        return baseMapper.selectInfoWebById(id);
    }

    @Override
    public void updatePageViewCount(String id) {
        EduCourse course = baseMapper.selectById(id);
        course.setViewCount(course.getViewCount() + 1);
        baseMapper.updateById(course);
    }

}
